#include "timer.h"

static const char *TAG = "timer";
int touch_time = 0;
gptimer_handle_t gptimer_handle = NULL;

extern btn_struct btn;
extern touch_status touch_sta;
extern QueueHandle_t btn_data;
bool alarm_cb_t(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    btn.flag = 1;                               // 设置按键的状态为短按
    touch_sta = touch_zero;                     // 清除touch的状态
    btn.touch = touch_sta;                      // 将当前的touch状态赋值给结构体
    gptimer_stop(gptimer_handle);               // 停止计时器
    gptimer_disable(gptimer_handle);            // 关闭计时器
    gptimer_del_timer(gptimer_handle);          // 删除定时器
    xQueueSendFromISR(btn_data, &btn, pdFALSE); // 发送数据
    return true;
}
void timer_init(void)
{

    gptimer_config_t config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT, // 选择定时器的时钟源
        .direction = GPTIMER_COUNT_UP,      // 向上计数模式
        .resolution_hz = 1000000,           // 1us精度
    };
    ESP_ERROR_CHECK(gptimer_new_timer(&config, &gptimer_handle));

    // // 配置报警结构体参数
    // gptimer_alarm_config_t alarm_config = {
    //     .reload_count = 0,                  // 重载计数值为0
    //     .alarm_count = 1000000,             // 报警目标计数值，1s
    //     .flags.auto_reload_on_alarm = true, // 开启重加载
    // };
    // ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer_handle, &alarm_config)); // 设置定时器的报警事件

    // 配置回调函数
    const gptimer_event_callbacks_t cbs = {
        .on_alarm = alarm_cb_t,
    };
    ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer_handle, &cbs, NULL));
    // ESP_ERROR_CHECK(gptimer_enable(gptimer_handle));
}